package com.mr.qa.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Transaction;

import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.bo.ShopCategory;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.ShopCategoryForm;
import com.mr.qa.util.HibernateSessionFactory;

public class ShopCategoryAction extends BaseAction {

	@Override
	public ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionForward af = null;
        ActionMessages errors = new ActionMessages();
        ActionMessages messages = new ActionMessages();
        UserSession us = null;
        us = UserSessionUtil.getUserSession(request);
        String action = this.getAction(request);
        ShopCategoryForm categoryForm = (ShopCategoryForm)form;

        if(us == null)
        {
            errors.add("relogin", new ActionMessage("login.required"));
            action = "login";
        }
        
        if ("admin".equals(action)) {
			if (!"1".equals(us.getType())) {
				errors.add("login", new ActionMessage("admin.requireadmin"));
				action = "relogin";
			} else {
				List list = getAvailCategoryList();
				request.setAttribute("list", list);
				request.setAttribute("cresultSize", list==null?1:list.size());
			}
		}else if("add".equals(action)){
			addCategory(categoryForm);
			String path = mapping.findForward(action).getPath();
			af = new ActionForward(path);
            af.setRedirect(true);
		}else if("get".equals(action)){
			ShopCategory category = getCategory(categoryForm);
			request.setAttribute("shopCategory", category);
		}else if("update".equals(action)){
			updateCategory(categoryForm);
			String path = mapping.findForward(action).getPath();
			af = new ActionForward(path);
            af.setRedirect(true);
		}else if("predelete".equals(action)){
			checkDelete(categoryForm, errors);
			if(!errors.isEmpty()){
				af = mapping.findForward("get");
			}
			request.setAttribute("categoryId", categoryForm.getCategoryId());
		}else if("delete".equals(action)){
			if(deleteCategory(categoryForm, errors, request)){
				String path = mapping.findForward(action).getPath();
				af = new ActionForward(path);
				af.setRedirect(true);
			}else{
				request.setAttribute("categoryId", categoryForm.getCategoryId());
				af = mapping.findForward("predelete");
			}
		}

        if(af == null)
        {
            af = mapping.findForward(action);
        }
        if(errors.size() > 0)
        {
            saveErrors(request, errors);
            if(af.getRedirect())
            saveErrors(request.getSession(), errors);
        }
        if(messages.size() > 0)
        {
            saveMessages(request, messages);
            if(af.getRedirect())
            saveMessages(request.getSession(), messages);
        }
        return af;
	}
	
	private void addCategory(ShopCategoryForm form) throws QaException {
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			ShopCategory category = new ShopCategory();
			category.setName(form.getName());
			category.setEmail(form.getEmail());
			category.add();
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw new QaException(e);
		} finally {
            HibernateSessionFactory.closeSession();
        }  
	}
	
	private ShopCategory getCategory(ShopCategoryForm form) throws QaException {
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			ShopCategory category = new ShopCategory();
			Integer id = Integer.valueOf(form.getCategoryId());
			category = category.getById(id);
			tx.commit();
			return category;
		} catch (Exception e) {
			tx.rollback();
			throw new QaException(e);
		} finally {
            HibernateSessionFactory.closeSession();
        }  
	}
	
	private void updateCategory(ShopCategoryForm form) throws QaException {
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			ShopCategory category = new ShopCategory();
			Integer id = Integer.valueOf(form.getCategoryId());
			category.setId(id);
			category.setName(form.getName());
			category.setEmail(form.getEmail());
			category.update();
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw new QaException(e);
		} finally {
            HibernateSessionFactory.closeSession();
        }  
	}
	
	private List getAvailCategoryList() throws QaException {
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			ShopCategory category = new ShopCategory();
			List list = category.getAvailCategories();
			tx.commit();
			return list;
		} catch (Exception e) {
			tx.rollback();
			throw new QaException(e);
		} finally {
            HibernateSessionFactory.closeSession();
        }  
	}
	
	private void checkDelete(ShopCategoryForm form, ActionMessages errors) throws QaException {
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			ShopCategory category = new ShopCategory();
			Integer id = Integer.valueOf(form.getCategoryId());
			int count = category.countArticle(id);
			if (count > 0) {
				category = category.getById(id);
				errors.add("error", new ActionMessage(
						"shopcategory.delete.article", category.getName()));
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw new QaException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}
	
	private boolean deleteCategory(ShopCategoryForm form, ActionMessages errors, HttpServletRequest request) throws QaException {
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			ShopCategory category = new ShopCategory();
			Integer id = Integer.valueOf(form.getCategoryId());
			category = category.getById(id);
			String vc = form.getVc();
            if(vc == null || vc.length() < 4)
            {
                errors.add("vc", new ActionMessage("verificationcode.required"));
                return false;
            }
            
			String vcInSession = UserSessionUtil.getVerificationCodes(request);
			if (!vcInSession.equals(vc)){
				errors.add("vc", new ActionMessage("verificationcode.error"));
				return false;
			}
				
			int success = category.deleteCategory();
			if (success == 1) {
				category = category.getById(id);
				errors.add("error", new ActionMessage(
						"shopcategory.delete.article", category.getName()));
				return false;
			}
			tx.commit();
			return true;
		} catch (Exception e) {
			tx.rollback();
			throw new QaException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

}
